<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="分类" prop="catalogId">
        <el-select
          v-model="queryParams.catalogId"
          placeholder="请选择分类"
          clearable
        >
          <el-option
            v-for="item in cateList"
            :key="item.catId"
            :label="item.name"
            :value="item.catId"
          >
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="品牌" prop="brandId">
        <el-input
          v-model="queryParams.brandId"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上架" prop="publishStatus">
        <el-select
          v-model="queryParams.publishStatus"
          placeholder="请选择上架状态"
          clearable
        >
          <el-option
            v-for="dict in publish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['product:spuInfo:add']"
          >新增</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:spuInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:spuInfo:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="spu_id" align="center" prop="spuId" />
      <el-table-column label="商品名称" align="center" prop="spuName" />
      <el-table-column label="描述信息" align="center" prop="spuDescription" />
      <el-table-column label="分类" align="center" prop="catName" />
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column label="上架状态" align="center" prop="publishStatus">
        <template #default="scope">
          <dict-tag
            :options="publish_status"
            :value="scope.row.publishStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="100"
      >
        <template #default="scope">
          <div class="table-operation">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleImages(scope.row)"
              v-hasPermi="['product:spuInfo:edit']"
              >图集</el-button
            >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleAttr(scope.row)"
              v-hasPermi="['product:spuInfo:edit']"
              >属性</el-button
            >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleRelease(scope.row)"
              v-hasPermi="['product:spuInfo:edit']"
              v-if="scope.row.publishStatus != 1"
              >上架</el-button
            >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUnRelease(scope.row)"
              v-hasPermi="['product:spuInfo:edit']"
              v-if="scope.row.publishStatus == 1"
              >下架</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['product:spuInfo:remove']"
              >删除</el-button
            >
            <el-dropdown>
              <el-button link type="primary"
                >更多<el-icon class="el-icon--right"> <arrow-down /> </el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    ><router-link to="/marketing/fullReduction"
                      >编辑满减</router-link
                    ></el-dropdown-item
                  >
                  <el-dropdown-item
                    ><router-link to="/marketing/discount"
                      >编辑折扣</router-link
                    ></el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改spu信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="spuName">
          <el-input v-model="form.spuName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="描述信息" prop="spuDescription">
          <el-input
            :rows="5"
            type="textarea"
            v-model="form.spuDescription"
            placeholder="请输入描述信息"
          />
        </el-form-item>
        <el-form-item label="分类" prop="catalogId">
          <el-cascader
            v-model="form.originIds"
            :options="cateList"
            @change="getBrandOptions"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择品牌" clearable>
            <el-option
              v-for="item in brandList"
              :key="item.brandId"
              :label="item.brandName"
              :value="item.brandId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="上架状态" prop="publishStatus">
          <el-radio-group v-model="form.publishStatus">
            <el-radio
              v-for="dict in publish_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改spu attr信息 -->
    <el-dialog :title="title" v-model="attrOpen" width="800px" append-to-body>
      <el-table :data="attrList" border stripe>
        <el-table-column
          label="属性名称"
          prop="attrName"
          width="80"
        ></el-table-column>
        <el-table-column label="属性值" prop="valueSelect">
          <template #default="scope">
            <el-radio-group
              v-if="scope.row.valueSelect.length > 1"
              v-model="attrForm[scope.$index].attrValue"
            >
              <el-radio
                v-for="(item, index) in scope.row.valueSelect"
                :key="index"
                :label="item"
              >
                {{ item }}
              </el-radio>
            </el-radio-group>
            <el-input
              v-model="attrForm[scope.$index].attrValue"
              style="width: 200px"
              v-else
            >
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div
        style="
          margin-top: 10px;
          display: flex;
          flex-direction: flex-end;
          width: 100%;
        "
      >
        <el-button type="primary" @click="submitAttrForm">确定</el-button>
        <el-button @click="attrOpen = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 修改spu images信息 -->
    <el-dialog
      :title="title"
      v-model="imageOpen"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-popover
        placement="right"
        :width="500"
        :visible="isAddImg"
        trigger="click"
      >
        <template #reference>
          <el-button
            size="small"
            icon="Upload"
            type="primary"
            @click="handleAddImg"
            style="margin-bottom: 10px"
            >添加图片</el-button
          >
        </template>
        <el-form ref="imgFormRef" :model="imgForm" :rules="imgRules">
          <el-form-item label="排序" prop="imageSord">
            <el-input-number
              v-model="imgForm.imageSord"
              controls-position="right"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="图片" prop="imageUrl">
            <image-upload
              v-model="imgForm.imageUrl"
              :limit="1"
              :width="60"
              :height="60"
            ></image-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitImgForm">确定</el-button>
            <el-button @click="isAddImg = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-popover>

      <el-table :data="imageList" border stripe>
        <el-table-column label="序号" prop="id" width="80"></el-table-column>
        <el-table-column label="图片" align="center" prop="skuDefaultImg">
          <template #default="scope">
            <image-preview :src="scope.row.imageUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          prop="imageSord"
          width="80"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              link
              size="small"
              type="primary"
              icon="Edit"
              @click="handleUpdateImg(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              size="small"
              type="danger"
              icon="Delete"
              @click="handleDelImg(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
import {
  listSpuInfo,
  getSpuInfo,
  delSpuInfo,
  addSpuInfo,
  updateSpuInfo,
  releaseSpu,
  unReleaseSpu,
  updateSpu2Attr,
} from "@/api/mall/server/product/maintain/spu";
import {
  listSpuImagesBySpuId,
  addSpuImages,
  updateSpuImages,
  delSpuImages,
} from "@/api/mall/server/product/maintain/spuImages";
import { listTreeCategories } from "@/api/mall/server/product/cate";
import {
  listBaseAttrValueBySpu,
  listBaseAttrBySpu,
} from "@/api/mall/server/product/attribute";
import { listBrandByCate } from "@/api/mall/server/product/relation";
import { watch } from "vue";
const { proxy } = getCurrentInstance();
const { publish_status } = proxy.useDict("publish_status");
const total = ref(0);
const loading = ref(false);
const list = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const open = ref(false);
const formRef = ref();
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {},
});
const { queryParams, form, rules } = toRefs(data);

// 图片管理
const isAddImg = ref(false);
const imgForm = ref({});
const imgRules = reactive({
  imageUrl: {
    required: true,
    message: "图片不能为空",
  },
  imageSord: {
    required: true,
    message: "排序不能为空",
  },
});
const imgFormRef = ref();
const handleAddImg = () => {
  imgForm.value.id = undefined;
  imgForm.value.imageUrl = undefined;
  imgForm.value.imageSord = undefined;
  isAddImg.value = true;
};
const handleUpdateImg = async (row) => {
  imgForm.value = JSON.parse(JSON.stringify(row));
  isAddImg.value = true;
};
const handleDelImg = async (row) => {
  proxy.$modal.confirm("确定删除SPU图片集？").then(async () => {
    let spuId = row.spuId;
    const res = await delSpuImages(row.id);
    proxy.$message.success("删除成功");
    handleImages({ spuId: spuId });
  });
};
const submitImgForm = () => {
  console.log(imgForm.value);
  imgFormRef.value.validate((valid) => {
    if (valid) {
      if (imgForm.value.id != undefined) {
        updateSpuImages(imgForm.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          handleImages(imgForm.value);
          isAddImg.value = false;
        });
      } else {
        addSpuImages(imgForm.value).then((res) => {
          proxy.$modal.msgSuccess("添加成功");
          handleImages(imgForm.value);
          isAddImg.value = false;
        });
      }
    }
  });
};
// 列表查询
const getList = async () => {
  loading.value = true;
  const res = await listSpuInfo(queryParams.value);
  list.value = res.rows;
  loading.value = false;
};

// 上架
const handleRelease = (row) => {
  proxy.$modal.confirm("是否将该商品上架？").then(async () => {
    const res = await releaseSpu(row.spuId);
    proxy.$message.success("上架成功");
    getList();
  });
};
// 下架
const handleUnRelease = (row) => {
  proxy.$modal.confirm("是否将该商品下架？").then(async () => {
    const res = await unReleaseSpu(row.spuId);
    proxy.$message.success("下架成功");
    getList();
  });
};
// 图片
const imageOpen = ref(false);
const imageList = ref([]);
const handleImages = async (row) => {
  title.value = "修改商品介绍图集";
  console.log("scope", row);
  const res = await listSpuImagesBySpuId(row.spuId);
  imageList.value = res.data;
  imageOpen.value = true;
  imgForm.value.spuId = row.spuId;
};
watch(
  () => isAddImg.value,
  (val) => {
    if (!val) {
      imgForm.value.id = undefined;
      imgForm.value.imageUrl = undefined;
      imgForm.value.imageSord = undefined;
      imgForm.value.note = undefined;
    }
  }
);

// 编辑属性
const attrOpen = ref(false);
const attrList = ref([]);
const handleAttr = async (row) => {
  title.value = "修改商品SPU属性";
  console.log("scope", row);
  Promise.all([getBaseAttrValue(row.spuId), getBaseAttr(row.spuId)]).then(
    (res) => {
      attrOpen.value = true;
    }
  );
};

const attrForm = ref([]);
const submitAttrForm = async () => {
  console.log("form", attrForm.value);
  await updateSpu2Attr(attrForm.value).then((res) => {
    proxy.$modal.msgSuccess("修改成功");
    getList();
    attrOpen.value = false;
  });
};
// 获取baseAttrValue
const getBaseAttrValue = async (spuId) => {
  const res = await listBaseAttrValueBySpu(spuId);
  attrForm.value = res.data;
  console.log("attrForm", attrForm.value);
};
// 获取baseAttr
const getBaseAttr = async (spuId) => {
  const res = await listBaseAttrBySpu(spuId);
  // 修改valueSelect
  attrList.value = res.data;
  attrList.value.map((item) => {
    return (item.valueSelect = item.valueSelect.split(","));
  });
  console.log("attrList", attrList.value);
};

// 取消
const cancel = () => {
  open.value = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    spuId: undefined,
    spuName: undefined,
    spuDescription: undefined,
    catalogId: undefined,
    brandId: undefined,
    publishStatus: undefined,
    createTime: undefined,
    updateTime: undefined,
  };
};
// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 表单重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.spuId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
// 添加弹窗
const handleAdd = (row) => {
  reset();
  open.value = true;
  title.value = "添加商品SPU信息";
};
// 修改操作
const handleUpdate = async (row) => {
  reset();
  const spuId = row.spuId || ids.value;
  const res = await getSpuInfo(spuId);
  form.value = res.data;
  console.log(cateList.value);
  console.log("form", form.value.originIds);
  await getBrandList();
  open.value = true;
  title.value = "修改商品SPU信息";
};
// 表单提交
const submitForm = () => {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.spuId != undefined) {
        updateSpuInfo(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSpuInfo(form.value).then((res) => {
          proxy.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

// 删除
const handleDelete = (row) => {
  const ids = row.spuId || ids.value;
  proxy.$modal
    .confirm(`是否确认删除编号位${ids}的数据项?`)
    .then((res) => {
      return delSpuInfo(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

// 筛选catId
const selectCatalog = (arr, catId) => {
  let _arr = [];
  // 遍历
  for (let index = 0; index < arr.length; index++) {
    const e = arr[index];
    _arr.push(e.value);
    if (e.value == catId) {
      break;
    } else {
      if (e.children && e.children.length > 1) {
        _arr.push(e.value);
        for (let _index = 0; _index < e.children.length; _index++) {
          const e1 = e.children[_index];
          if (e1.value == catId) {
            _arr.push(e1.value);
            break;
          } else {
            if (e1.children && e1.children.length > 1) {
              _arr.push(e1.value);
              let index = e1.children.findIndex((item) => item.value == catId);
              if (index > -1) {
                _arr.push(e1.children[index].value);
                break;
              } else {
                _arr.pop();
                _arr.pop();
              }
            } else {
              _arr.pop();
            }
          }
        }
      } else {
        _arr.pop();
      }
    }
  }
  return _arr;
};
// 查询分类
const cateList = ref([]);
const getTreeCategory = async () => {
  const res = await listTreeCategories();
  // 处理cate
  const list = res.data;
  cateList.value = formatList(list);
};
// 替换字段
const formatList = (list) => {
  return list.map((item) => {
    return {
      value: item.catId,
      label: item.name,
      children: item.children ? formatList(item.children) : [],
    };
  });
};

// 查询品牌
const brandList = ref([]);
const getBrandOptions = async () => {
  form.value.brandId = undefined;
  console.log("品牌变化", form.value);
  form.value.catalogId = form.value.originIds[form.value.originIds.length - 1];
  const res = await listBrandByCate(form.value.catalogId);
  brandList.value = res.data;
};

const getBrandList = async () => {
  const res = await listBrandByCate(form.value.catalogId);
  brandList.value = res.data;
};
// const getBrandByCategory = async (id) => {
//   const res = await listBrandByCategory(id);
//   brandList.value = res.data;
// };

// 监听
watch(
  () => form.value.catalogId,
  (val) => {
    console.log("分类", val);

    // getBrandByCategory(val);
  }
);
getList();
getTreeCategory();
</script>

<style lang="scss" scoped>
.table-operation {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .el-button {
    margin-left: 0;
    margin-top: 2px;
  }
}
</style>
